<?php

namespace services\member;

use common\components\Service;
use common\models\member\Member;
use common\models\member\MemberDepartment;
use services\base\DepartmentService;
use services\rbac\RoleService;
use Yii;

/**
 * Class MemberDepartmentService
 * @package services\member
 *
 */
class MemberDepartmentService extends Service
{
    /**
     * 根据项目ID查找用户IDs
     * @param $departmentIds
     * @return int[]
     */
    public static function getMemberIdsByDepartmentId($departmentIds): array
    {
        return MemberDepartment::find()
            ->select(['member_id'])
            ->where(['department_id' => $departmentIds])
            ->column();
    }

    /**
     * 根据人员ID查找用户绑定部门IDs
     * @param $departmentIds
     * @return int[]
     */
    public static function getDepartmentIdsByMemberId($memberIds): array
    {
        return MemberDepartment::find()
            ->select(['department_id'])
            ->where(['member_id' => $memberIds])
            ->column();
    }

    /**
     * 获取用户绑定部门默认角色Ids
     * @param int $memberId
     * @return array
     */
    public static function getUserRoleEnableIds(int $memberId): array
    {
        $departmentList = DepartmentService::getEnableListByIds(self::getDepartmentIdsByMemberId($memberId));
        $roleIds = array_column($departmentList, 'default_role_id');
        $roleList = RoleService::getEnableListByIds($roleIds);
        return $roleList ? array_column($roleList, 'id') : [];
    }

    /**
     * 编辑部门
     * @param Member $member
     * @param array $ids
     * @return void
     * @throws \Exception
     */
    public static function editModel(Member $member, array $ids): void
    {
        MemberDepartment::deleteAll(['member_id' => $member->id]);
        $data = [];
        foreach ($ids as $id) {
            $data[] = [
                $member->id,
                $id
            ];
        }
        Yii::$app->db->createCommand()->batchInsert(
            MemberDepartment::tableName(),
            ['member_id', 'department_id'],
            $data
        )->execute();
    }

    /**
     * 解绑部门
     * @param int|array $departmentIds
     * @return void
     */
    public static function unBindDepartment($departmentIds): void
    {
        MemberDepartment::deleteAll(['department_id' => $departmentIds]);
    }
}
